//app.js
import GlobalConfig from './config/index'
const globalConfig = new GlobalConfig()
globalConfig.init()
var URLT = 'http://gift.coman99.com/super/public/index.php/appapi/';
var USER_id;
var SHARE_id;
var VISTER_id;
App({
  onLaunch: function(options) {
    console.log('获取转发消息', '分享:' + options.scene)
    if (options.scene == 1044) {
      if (options.shareTicket)
        SHARE_id = options.shareTicket;
      console.log('群ID', SHARE_id)
    }
    // 展示本地存储能力
    var logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs)
    this.getReaderSize();
    this.onLogin();
  },
  onLogin: function (name ='return'){
    var that = this;
    wx.login({
      success: res => {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
        wx.request({
          url: URLT + 'We_Registerland/getUserId',
          data: {
            code: res.code
          },
          header: {
            'Content-Type': 'application/x-www-form-urlencoded'
          },
          success: function (res) {
            console.log('登录成功返回信息', res)
            if (res.data.code == 10001) {
              USER_id = res.data.data.uid;
              that.globalData.ss_key = res.data.data.ss_key;
              if (name == 'return'){
                console.log('返回主页' + name)
                wx.switchTab({
                  url: '../userInfo/index',
                })
              }
            } else {
              // that.prompt('登陆失败');
              that.goBackUser();
            }
          },
          fail: function (res) {
            console.log('失败信息', res)
            that.prompt('网络异常');
          }
        })
      }
    });
    // 检测登录
    // wx.checkSession({　　　　
    //   success: function(res) {       　　　　　　
    //     console.log("处于登录态");       　　　　
    //   },
    //   fail: function(res) {       　　　　　　
    //     console.log("需要重新登录");
    //     wx.login({
    //       success: res => {
    //         // 发送 res.code 到后台换取 openId, sessionKey, unionId
    //         wx.request({
    //           url: URLT + 'We_Registerland/getUserId',
    //           data: {
    //             code: res.code
    //           },
    //           header: {
    //             'Content-Type': 'application/x-www-form-urlencoded'
    //           },
    //           success: function(res) {
    //             console.log('登录成功返回信息', res)
    //             if (res.data.code == 10001) {
    //               USER_id = res.data.data.uid;
    //               that.globalData.ss_key = res.data.data.ss_key;
    //             } else {
    //               that.prompt('登陆失败');
    //               that.goBackUser();
    //             }
    //           },
    //           fail: function(res) {
    //             console.log('失败信息', res)
    //             that.prompt('网络异常');
    //           }
    //         })
    //       }
    //     })       　　　　
    //   }     　　
    // })
  },
  goBackUser: function() {
    console.log('返回上一页')
    wx.navigateBack({
      delta: 1
    })
  },
  globalData: {
    config: globalConfig,
    shareImg: '/images/icon/redbag.png',
    userInfo: null,
    ss_key: '',
    windowHeight: '',
    windowWidth: '',
  },
  getReaderSize: function() {
    var that = this;
    wx.getSystemInfo({
      success: function(res) {
        console.log(res);
        // 屏幕宽度、高度
        console.log('height=' + res.screenHeight);
        console.log('width=' + res.screenWidth);
        // 高度,宽度 单位为px
        that.globalData.windowHeight = res.screenHeight;
        that.globalData.windowWidth = res.screenWidth;
      }
    })
  },
  /**
   * 授权获取用户信息
   */
  getUserInfo: function(contr, mid = '', sid = '', rid = '') {
    var that = this;
    // 获取用户信息
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo']) {
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
          wx.getUserInfo({
            lang: 'zh_CN',
            success: res => {
              console.log('appjs初始化页面获取用户信息' + '被访问的用户id：' + mid)
              // 可以将 res 发送给后台解码出 unionId
              var data = res.userInfo;
              data['logTmid'] = mid;
              data['logTsid'] = sid;
              data['logTrid'] = rid;
              var url = 'We_Registerland/updateUserInfo';
              that.globalData.userInfo = data
              that.netWorkRequest(contr, data, url, 'startUser');
              // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
              // 所以此处加入 callback 以防止这种情况
              if (that.userInfoReadyCallback) {
                that.userInfoReadyCallback(res)
              }
            }
          })
        } else {
          contr.getUserInfo();
          // wx.switchTab({
          //   url: '../home/index'
          // })
        }
      }
    })
  },
  getUserQrcode: function(path, val) {
    wx.request({
      url: URLT + 'We_Registerland/getWecode',
      method: 'POST',
      data: {
        path: path,
        val: val
      },
      header: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      success: function(res) {
        wx.setStorageSync('weackcode', res.data.data);
      },
      fail: function(res) {
        that.prompt('获取二维码失败');
      }
    })
  },
  //网络请求
  netWorkRequest: function(contr, t_data = [], url = '', name = '', post = "POST") {
    var that = this
    if (!t_data['uid'] || t_data['uid'] == '') {
      t_data['uid'] = USER_id;
    }
    console.log('首次传递参数', t_data, name)
    if (name == 'startUser' && (!t_data['uid'] || t_data['uid'] == 'undefined' || t_data['uid'] == undefined || t_data['uid'] == '')) {
      console.log('uid延迟' + t_data['uid'])
      // //防止页面加载延迟
      return contr.getUserInfo();
    }
    var url = URLT + url
    wx.request({
      url: url, //仅为示例，并非真实的接口地址
      method: post,
      data: t_data,
      header: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      success: function(res) {
        console.log('首次传递统一返回信息', res)
        var resdata = res.data
        if (resdata.code == 10003 || resdata.code == '10003'){
          console.log('登录超时,清缓存')
          try {
            wx.removeStorageSync('userInfo')
          } catch (e) {
            console.log('清缓存失败'+e)
          }
          return that.onLogin('return');
        }
        var data = resdata.data
        if (name == 'startUser') {
          if (resdata.code == 10001) {
            wx.setStorage({
              key: 'userInfo',
              data: data,
              success: function(e) {
                // if (t_data['logTmid'] && t_data['logTmid'] !='') {
                //   VISTER_id = t_data['logTsid'];
                //   if (t_data['logTmid'] == USER_id) { //如果是本人
                //     console.log('是本人操作' + USER_id)
                //     wx.switchTab({
                //       url: '../userInfo/index'
                //     })
                //   } else {
                //     console.log('非本人操作' + t_data['logTmid'])
                //     if (VISTER_id == USER_id && SHARE_id && SHARE_id != undefined){//如果分享者和访问者相同且是分享到群里的
                //       console.log('分享者和访问者相同且是分享到群里的')
                //       wx.navigateTo({
                //         url: '../visitorInfo/index?id=' + t_data['logTmid'] + '&sid=' + t_data['logTsid'] + '&rid=' + t_data    ['logTrid']
                //       })
                //     }else{
                //       console.log('分享者和访问者相同但不是分享到群里的')
                //       wx.navigateTo({
                //         url: '../visitorInfo/index?id=' + t_data['logTmid']
                //       })
                //     }
                //   }

                // } else {
                //   console.log('缓存信息成功回到主页' + USER_id)
                //   contr.onPullDownRefresh();
                // }
                console.log('缓存信息成功回到主页' + USER_id)
                contr.onPullDownRefresh();
              },
              fail: function(e) {
                console.log('缓存失败重新授权用户操作',e)
                return contr.getUserInfo();
              }
            })
          } else {
            that.prompt(resdata.msg);
          }
        } else if (name == 'userList') {
          if (resdata.code == 10001) {
            contr.setData({
              userList: data
            })
          } else {
            that.prompt(resdata.msg);
          }
        } else if (name == 'userMessage') {
          if (resdata.code == 10001) {
            contr.setData({
              userMessage: data
            })
          }
        } else if (name == 'wxpay') {
          if (resdata.code == 10001) {
            contr.paymentTransfer(data);
          } else {
            that.promptModal(resdata.msg);
          }
        } else if (name == 'userBasic') {
          if (resdata.code == 10001) {
            contr.setData({
              userBasic: data
            })
          } else {
            that.prompt(resdata.msg);
          }
        } else if (name == 'cashBlanc') {
          contr.onPullDownRefresh();
          if (resdata.code == 10001) {
            //that.promptModal(resdata.msg)
            wx.showModal({
              title: '提示信息',
              content: resdata.msg,
              showCancel: false,
              success: function (res) {

              }
            })
          } else {
            that.promptModal(resdata.msg)
          }
        } else if (name == 'basicInfo') {
          if (resdata.code == 10001) {
            contr.setData({
              basicInfo: data
            })
          } else {
            that.prompt(resdata.msg);
          }
        } else if (name == 'userCardInfo') {
          if (resdata.code == 10001) {
            if (data['Introduce'] && data['Introduce'] !== '' && data['Introduce'] != undefined)
              data['IntState'] = that.exceptLengthLine(data['Introduce']);
            contr.setData({
              userCardInfo: data
            })
          } else {
            that.prompt(resdata.msg);
          }
        } else if (name == 'redPackRand') {
          contr.setData({
            redPackRand: data
          })
          console.log('领取次数' + data['Redpack_num'])
          console.log('类型' + data['cotype'])
          if (data['rid']) {
            if (data['Redpack_State']) {
              console.log('渠道' + data['Redpack_num'])
              contr.resetCoverImg();
            }
            contr.getAppointRedpagList(data['rid'])
          }
          if (resdata.code != 10001 && data['cotype'] == 'code') {
            that.promptModal(resdata.msg);
          }

        } else if (name == 'redRecMind') {
          contr.setData({
            redRecMind: data
          })

        } else if (name == 'redPackList') {
          if (resdata.code != 10001 && t_data['page'] == 1) {
            data = [];
          }
          contr.setData({
            redPackList: data
          })
        } else if (name == 'redPackAtil') {
          if (resdata.code == 10001) {
            contr.setData({
              redPackAtil: data
            })
          } else {
            that.prompt(resdata.msg)
          }

        } else if (name == 'BrowseNum') {
          console.log('热点记录')
        } else if (name == 'reaPackReceive') {
          contr.setData({
            reaPackReceive: data
          })
          contr.getOtherUserInfo();
          if (resdata.code == 10001) {
            var msg = '恭喜你抢到了' + data.Amount + '元';
            that.promptModal(resdata.msg)
          } else {

          }
        } else if (name == 'messageList') {
          if (resdata.code != 10001 && t_data['page'] == 1) {
            data = [];
          }
          contr.setData({
            messageList: data
          })
        } else if (name == 'messageAtils') {
          if (resdata.code != 10001 && t_data['page'] == 1) {
            data = [];
          }
          contr.setData({
            messageAtils: data
          })
        } else if (name == 'messageCodeList') {
          if (resdata.code != 10001 && t_data['page'] == 1) {
            data = [];
          }
          contr.setData({
            messageCodeList: data
          })
        } else if (name == 'regionDatas') {
          if (resdata.code == 10001) {
            contr.initRegionData(data)
          } else {
            that.prompt('网络异常');
          }
        } else if (name == 'phoneNumber') {
          if (resdata.code == 10001) {
            contr.updatePhone(data['phoneNumber'])
          } else {
            that.promptModal(resdata.msg);
          }
        } else if (name == 'giveUpAdd') {

          if (resdata.code == 10001) {
            var t = contr.data.userCardInfo;
            t['Giveup_state'] = true;
            t['Giveup_volume'] += 1;
            contr.setData({
              userCardInfo: t
            })
          } else {
            that.promptModal(resdata.msg);
          }
        } else if (name == 'giveUpDell') {

          if (resdata.code == 10001) {
            var t = contr.data.userCardInfo;
            t['Giveup_state'] = false;
            t['Giveup_volume'] -= 1;
            contr.setData({
              userCardInfo: t
            })
          } else {
            that.promptModal(resdata.msg);
          }
        } else if (name == 'Introduce') {
          if (resdata.code == 10001) {
            that.prompt(resdata.msg, 'success');
            contr.updateIntroduce(data['Introduce'])
          } else {
            that.promptModal(resdata.msg);
          }
        } else if (name == 'perfectInfo') {
          contr.onLoad();
          if (resdata.code == 10001) {
            that.goBackUser();
            // that.prompt('更新成功', 'success');
          } else {
            that.prompt(resdata.msg);
          }
        } else if (name == 'addMessage') {
          if (resdata.code == 10001) {
            contr.setData({
              bgmState:true
            })
            that.prompt('留言成功', 'success');
          } else {
            that.prompt(resdata.msg);
            contr.onShow();
          }
        } else if (name == 'addMessageCode') {
          if (resdata.code == 10001) {
            that.prompt('回复成功', 'success');
            contr.onShow();
          } else {
            that.prompt(resdata.msg);
          }
        } else if (name == 'updatePoster') {
          if (resdata.code == 10001) {
            that.prompt('删除成功', 'success');
            contr.updatePoster(data);
          } else {
            that.prompt(resdata.msg);
          }
        }
      },
      fail: function() {
        that.prompt()
      },
      complete: function() {
        wx.stopPullDownRefresh()
        wx.hideNavigationBarLoading()
      }
    })
  },
  //网络请求(加载更多)
  netWorkRequestLoadMore: function(contr, t_data = [], url = '', name = '', f_data = [], post = "POST") {
    var that = this
    if (!t_data['uid'] || t_data['uid'] == '') {
      t_data['uid'] = USER_id;
    }
    console.log('传递参数', t_data, name)
    var url = URLT + url
    wx.request({
      url: url, //仅为示例，并非真实的接口地址
      method: post,
      data: t_data,
      header: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      success: function(res) {
        console.log('加载更多返回信息', res)
        var resdata = res.data
        if (resdata.reland) {
          console.log('加载更多重新登陆')
          return that.onLaunch();
        }
        if (name == 'messageList') {
          if (resdata.code == 10001) {
            var data = resdata.data;
            for (var i = 0; i < data.length; i++) {
              f_data.push(data[i]);
            }
            contr.setData({
              messageList: f_data
            })
          } else {
            that.prompt('没有更多了')
          }
        }
        if (name == 'messageCodeList') {
          if (resdata.code == 10001) {
            var data = resdata.data;
            for (var i = 0; i < data.length; i++) {
              f_data.push(data[i]);
            }
            contr.setData({
              messageCodeList: f_data
            })
          } else {
            that.prompt('没有更多了')
          }
        } else if (name == 'userList') {
          if (resdata.code == 10001) {
            var data = resdata.data;
            for (var i = 0; i < data.length; i++) {
              f_data.push(data[i]);
            }
            contr.setData({
              userList: f_data
            })
          } else {
            that.prompt('没有更多了')
          }
        } else if (name == 'redPackList') {
          console.log('加载更多', f_data)
          if (resdata.code == 10001) {
            var data = resdata.data;
            for (var i = 0; i < data.length; i++) {
              f_data.push(data[i]);
            }
            contr.setData({
              redPackList: f_data
            })
          } else {
            that.prompt('没有更多了')
          }
        }
      },
      fail: function() {
        that.prompt()
      },
      complete: function() {
        wx.hideLoading();
        wx.stopPullDownRefresh();
        wx.hideNavigationBarLoading();
      }
    })
  },
  //分享转发
  onShareAppMessage: function(res, title = '超级人脉', path = 'pages/home/index') {
    console.log('统一转发', res)
    return {
      title: title,
      path: path,
    }

  },
  //弹窗
  prompt: function(title = "网络繁忙，请稍后重试", icon = "loading", contr = '') {
    wx.showToast({
      title: title,
      icon: icon,
      duration: 2600
    })
  },
  //弹窗
  promptModal: function(cont = "提示信息", cancel = false, title = "提示信息") {
    wx.showModal({
      title: title,
      content: cont,
      showCancel: cancel,
      success: function(res) {
        if (res.confirm) {
          console.log('用户点击确定')
        }
      }
    })
  },
  //验证手机号
  testPhone: function(pho) {
    if (pho == '' || !pho) return false;
    var isMob = /^(13[0-9]|15[012356789]|18[02356789]|14[57]|17[0-9])[0-9]{8}$/
    if (!isMob.test(pho))
      return false;
    return true;
  },
  //本地背景图片转码
  baseImage: function(data) {
    let base64 = wx.getFileSystemManager().readFileSync(data, 'base64');
    return 'data:image/jpg;base64,' + base64;
  },
  //长按删除
  clickLongdeletion: function(contr, data, index, name) {
    wx.showModal({
      title: '提示',
      content: '确定要删除此图片吗？',
      success: function(res) {
        if (res.confirm) {
          console.log('点击确定了');
          data.splice(index, 1);
        } else if (res.cancel) {
          console.log('点击取消了');
          return false;
        }
        contr.setData({
          reaPackList: data
        });
      }
    })
  },
  //上传海报
  uploadPoster: function(contr, count = 1, id) {
    var that = this;
    wx.chooseImage({
      count: count, // 默认9
      sizeType: ['compressed'],
      //sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function(res) {
        //缓存下 
        contr.setData({
          showLoading: true
        })
        //获取第一张图片地址 
        var tempFilePaths = res.tempFilePaths;
        console.log('上传图片' + tempFilePaths.length + '数量' + count)
        for (var i = 0; i < tempFilePaths.length; i++) {
          var filep = res.tempFilePaths[i];
          //向服务器端上传图片 
          wx.uploadFile({
            url: URLT + 'We_Businesscard/getUploadPosterLoading',
            filePath: filep,
            name: 'file',
            formData: {
              id: id,
              uid: USER_id
            },
            success: function(res) {
              console.log('返回图片' + res.data)
              var resdata = res.data;
              resdata = JSON.parse(resdata)

              if (resdata.code == '10001') {
                contr.setData({
                  showLoading: false
                })
                that.prompt(resdata.msg, 'success');
                var data = resdata.data
                contr.updatePoster(data)
              } else {
                that.prompt(resdata.msg);
              }
            },
            fail: function(res) {
              that.prompt();
            }
          });
        }
      }
    })
  },
  //上传图片
  uploadImage: function(contr, filep) {
    var that = this;
    //向服务器端上传图片 
    wx.uploadFile({
      url: URLT + 'We_Businesscard/getUploadFileLocal',
      filePath: filep,
      name: 'file',
      formData: {
        uid: USER_id
      },
      success: function(res) {
        console.log('返回图片' + res.data)
        var resdata = res.data;
        resdata = JSON.parse(resdata);
        var data = resdata.data;
        contr.updateHeadport(data)
        if (resdata.code == '10001') {
          that.prompt(resdata.msg, 'success');
        } else {
          that.prompt(resdata.msg);
        }
      },
      fail: function(res) {
        that.prompt();
      }
    });
  },
  /**   
   * 预览图片  
   */
  previewImage: function(current, list) {
    wx.previewImage({
      current: current, // 当前显示图片的http链接  
      urls: list // 需要预览的图片http链接列表  
    })
  },

  /**   
   * 计算字符占页面行数 
   */
  exceptLengthLine: function(str, pageWidth, margin = 20, size = 14, line = 5) {
    var that = this;
    var len = str.replace(/[\u0391-\uFFE5]/g, "aa").length;
    var pageWidth = that.globalData.windowWidth;
    if (pageWidth)
      pageWidth = pageWidth;
    var lenWidth = len * size / 2; //获取字符总长度
    var intWidth = (pageWidth - margin) * line //获取字符内容限定区总长度，不包括边距
    console.log('字符长度' + len)
    console.log('页面长度' + pageWidth)
    console.log('内容区总长度' + intWidth)
    console.log('字符总长度' + lenWidth)
    if (lenWidth > intWidth)
      return true;
    return false;
  },
})